package com.zhongmai.yzfgrabanorder.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 项目名称：YZFGrabAnOrder
 * 类描述：
 * 创建人：Administrator
 * 创建时间：2020/9/23 9:57
 * 修改人：Administrator
 * 修改时间：2020/9/23 9:57
 * 修改备注：
 */
public class EncryptUtils {
    private final static String DES = "desede";

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 加密
     * @param src 数据源
     * @param key 密钥，长度必须是8的倍数
     * @return 返回加密后的数据
     * @throws Exception
     */
    public static String encrypt(String src, String key, String iv) throws Exception {

        // 从原始密匙数据创建DESKeySpec对象
        DESedeKeySpec spec = new DESedeKeySpec(key.getBytes());
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(spec);
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, ips);
        // 现在，获取数据并加密
        // 正式执行加密操作(Base64.encodeBase64
        byte[] b = cipher.doFinal(src.getBytes("utf-8"));
        String str = new String(org.apache.commons.codec.binary.Base64.encodeBase64(cipher.doFinal(src.getBytes("utf-8"))));
        String result = byte2hex(str.getBytes("utf-8")).toUpperCase();
        return result;

    }


    /**
     * 解密
     * @param src 数据源
     * @param key 密钥，长度必须是8的倍数
     * @return 返回解密后的原始数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] src, byte[] key) throws Exception {

        // DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
        // 一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成解密操作
        Cipher cipher=Cipher.getInstance(DES);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
        // 现在，获取数据并解密
        // 正式执行解密操作
        byte[] bytes = cipher.doFinal(src);
        return cipher.doFinal(src);

    }

    /**
     * 二行制转字符串
     * @param b
     * @return
     */

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";

        for(int i = 0; i < b.length; ++i) {
            stmp = Integer.toHexString(b[i] & 255);
            if(stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }

        return hs;
    }
}
